﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Volo.Abp;
using Volo.Abp.Authorization;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Security.Claims;

namespace abp
{
//    [Dependency(ReplaceServices = true)]
    public class AuthorizationService: IAbpAuthorizationService,ITransientDependency
    {
        public IServiceProvider ServiceProvider { get; }
        public ClaimsPrincipal CurrentPrincipal => _currentPrincipalAccessor.Principal;

        private readonly ICurrentPrincipalAccessor _currentPrincipalAccessor;

        public AuthorizationService(ICurrentPrincipalAccessor currentPrincipalAccessor, IServiceProvider serviceProvider)
        {
            _currentPrincipalAccessor = currentPrincipalAccessor;
            ServiceProvider = serviceProvider;
        }


        public async Task<AuthorizationResult> AuthorizeAsync(ClaimsPrincipal user, object resource, IEnumerable<IAuthorizationRequirement> requirements)
        {
//            throw new NotImplementedException();
            if(CheckLogining(user)) throw new UserFriendlyException("用户未登入");

            Debug.WriteLine("测试授权");

            return await Task.Run(() => AuthorizationResult.Success());
        }

        private bool CheckLogining(ClaimsPrincipal user)
        {
            bool result = false;

            if (user != null)
            {
                var userClaim = user.FindFirst(a => a.Type == ClaimTypes.NameIdentifier);
                if (userClaim!=null&&!string.IsNullOrEmpty(userClaim.Value))
                {
                    //todo 校验mogodb是否登入
                }
            }

            return result;
        }

        public async Task<AuthorizationResult> AuthorizeAsync(ClaimsPrincipal user, object resource, string policyName)
        {
//            throw new NotImplementedException();

            Debug.WriteLine("测试授权");
            return await Task.Run(() => AuthorizationResult.Success());
        }
        

    }
}
